<?php
$xh = $_COOKIE['xh'];
$pwd = $_COOKIE['pwd'];
$rememberMe = $_COOKIE['rememberMe'];
if ($_POST) {
    try {
        echo '<pre>', print_r($_POST, true), '</pre>';
        if ($_POST['remember']) {//记住登录信息
            setcookie('xh', $_POST['xh'], time() + 7 * 24 * 3600);
            setcookie('pwd', $_POST['pwd'], time() + 7 * 24 * 3600);
            setcookie('rememberMe', $_POST['rememberMe'], time() + 7 * 24 * 3600);


        } else {//不用记住登录信息,就删除cookie信息
            setcookie('xh');
            setcookie('pwd');
            setcookie('rememberMe');
        }
        $db = new PDO("mysql:host=localhost;dbname=db3", 'root', '12qwas');
        $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        $ps = $db->prepare('select * from students where xh=? and pwd=?');
        $ps->execute([$_POST['xh'], $_POST['pwd']]);
        $r = $ps->fetch();

        session_start();//启动session
        if ($r == false) {//登录失败
            unset($_SESSION['user']);//删除登录的用户信息
            throw new Exception('你输入的用户名或口令不正确~');
        } else {//登录成功
            $_SESSION['user']=$r;//保存登录的用户信息
            header('Location:index.php');
            return;
        }
    } catch (Throwable $e) {
        $msg = $e->getMessage();
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>用户登录</title>
    <style>
        h1 {
            color: red;
        }

        input {
            padding: 6px;
            margin: 6px;
            border-radius: 6px;
        }

        .msg {
            color: red;
            margin: 20px 0;
        }
    </style>
</head>
<body>
<h1>用户登录</h1>
<form method="post">
    学号：<input type="text" name="xh" value="<?= $_POST['xh'] ?? $xh ?>"><br>
    密码：<input type="password" name="pwd" value="<?= $_POST['xh'] ?? $pwd ?>"><br>
    <input type="checkbox" name="rememberMe"<?=$_POST?($_POST['rememberMe']?' checked':''):($rememberMe=='on'?'checked':'')?>>记住我的信息一周<br>
    <div class="msg"><?=$msg?></div>
    <input type="submit"value="提交数据">
    <input type="button"value="注册新用户" onclick="location.href='modify.php'">
</form>
</body>
</html>